/**
 * 
 */
package com.hand.cloud.b2b.services.impl;

import de.hybris.platform.core.model.order.OrderModel;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hand.cloud.b2b.daos.EPLogisticsDAO;
import com.hand.cloud.b2b.daos.EPOrderDAO;
import com.hand.cloud.b2b.daos.OrderDAO;
import com.hand.cloud.b2b.daos.TBLogisticsDAO;
import com.hand.cloud.b2b.daos.TBTradeDAO;
import com.hand.cloud.b2b.model.EPLogisticsModel;
import com.hand.cloud.b2b.model.TB_LogisticsModel;
import com.hand.cloud.b2b.services.LogisticsService;
import com.hand.cloud.b2b.taobao.DefaultProperties;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.LogisticsOfflineSendRequest;
import com.taobao.api.response.LogisticsOfflineSendResponse;


/**
 * @author Snowling
 * 
 */
@Service(value = "logisticsService")
public class DefaultLogisticsService implements LogisticsService
{
	public static final Logger LOG = Logger.getLogger(DefaultLogisticsService.class);

	@Autowired
	OrderDAO orderDAO;

	@Autowired
	EPLogisticsDAO epLogisticsDAO;

	@Autowired
	EPOrderDAO epOrderDAO;

	@Autowired
	TBTradeDAO tbTradeDAO;

	@Autowired
	TBLogisticsDAO tbLogisticsDAO;

	/**
	 * 通过查询Hybris中已完成状态的订单，同步更新EP订单、TB订单的状态以及 创建EP、TB物流信息等操作
	 */
	@Override
	public void updateOrderStatus()
	{
		List<Object> list = new ArrayList<Object>();
		OrderModel order = new OrderModel();
		EPLogisticsModel epLogistics = new EPLogisticsModel();

		list = orderDAO.getCompletedOrders();


		for (int i = 0; i < list.size(); i++)
		{
			order = (OrderModel) list.get(i);

			epLogistics = epLogisticsDAO.createEPLogistics(order);

			epOrderDAO.changeEPOrderStatus(order);

			tbTradeDAO.changeTBTradeStatus(order.getEpOrder());

			final TB_LogisticsModel tbLogisitcs = tbLogisticsDAO.createTBLogistics(epLogistics);

			final TaobaoClient client = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
					DefaultProperties.appSecret);
			final LogisticsOfflineSendRequest req = new LogisticsOfflineSendRequest();

			// 192390290386705
			LOG.info(">>>>>>>>>>>>tid=" + tbLogisitcs.getTid());

			req.setTid(tbLogisitcs.getTid());
			req.setOutSid(tbLogisitcs.getOut_sid());
			req.setCompanyCode(tbLogisitcs.getCompany_code());

			try
			{
				final LogisticsOfflineSendResponse response = client.execute(req, DefaultProperties.sessionKey);
				System.out.println("response:::::::::::::::" + response.getBody());

				LOG.info("response:::::::::::::::" + response.getBody());
			}
			catch (final ApiException e)
			{
				e.printStackTrace();
			}
		}
	}
}
